import { delCollection, getCollectionList } from '@/services/ant-design-pro/brainSpace';
import { Empty, message, Pagination } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import ShortDocItem from '../ShortDocItem';
import './index.less';

const Collection: React.FC<any> = forwardRef((props: any, ref) => {
  const { title } = props;
  const [totalCount, setTotalCount] = useState<number>(0);
  const [dataList, setDataList] = useState<any[]>([]); // 文档列表

  const getCollection = async (page: number, per_page: number) => {
    const res = await getCollectionList({ page, per_page });
    if (res.code === 0) {
      const { total_count, articles } = res.data;
      setTotalCount(total_count);
      setDataList(articles);
    } else {
      message.error(res.msg);
    }
  };

  //分页默认值，
  const [pageOption, setPageOption] = useState({
    page: 1, //当前页为1
    per_page: 15, //一页15行
  });

  useImperativeHandle(ref, () => ({
    reloadData: () => {
      setPageOption({
        page: 1, //当前页为1
        per_page: 15, //一页15行
      });

      getCollection(1, 15);
    },
  }));

  //当翻页时，改变当前为第current页，current和size这两参数是onChange API自带的，会帮你算出来你现在在第几页，这一页有多少行数据。
  const paginationChange = async (current: number, size: number) => {
    //前面用到useState
    setPageOption({
      page: current, //当前所在页面
      per_page: size, //一页有几行
    });

    getCollection(current, size);
  };

  const deleteDoc = async (cognitionId: any) => {
    const res = await delCollection(cognitionId);
    if (res.code === 0) {
      message.success('删除成功');
      getCollection(pageOption.page, pageOption.per_page);
    } else {
      message.error(res.msg);
    }
  };

  useEffect(() => {
    getCollection(pageOption.page, pageOption.per_page);
  }, []);

  return (
    <div className="collection-warp">
      <div className="title">{title}</div>
      <div className="item-card-box">
        {dataList.length > 0 &&
          dataList.map((item: any) => {
            return <ShortDocItem key={item.id} item={item} deleteItem={deleteDoc}></ShortDocItem>;
          })}
        {!dataList.length && <Empty className="empty" image={Empty.PRESENTED_IMAGE_SIMPLE} />}
      </div>

      {dataList.length > 0 && (
        <div className="pagination flex-jcon-end m-t-10">
          <Pagination
            current={pageOption.page}
            defaultCurrent={1}
            pageSize={pageOption.per_page}
            total={totalCount}
            showSizeChanger={false}
            onChange={paginationChange}
          />
        </div>
      )}
    </div>
  );
});

export default Collection;
